<template>
  <a-form-model ref="ruleForm" :model="ruleForm" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 19 }">
    <a-form-model-item label="旧密码" prop="password">
      <a-input-password v-model="ruleForm.password" type="password"></a-input-password>
    </a-form-model-item>
    <a-form-model-item label="新密码" prop="newPassword" required>
      <a-input-password v-model="ruleForm.newPassword" type="password"></a-input-password>
    </a-form-model-item>
    <a-form-model-item label="确认密码" prop="confirmPassword" required>
      <a-input-password v-model="ruleForm.confirmPassword" type="password"></a-input-password>
    </a-form-model-item>
  </a-form-model>
</template>

<script>
import { editPassword } from '@/api/login'

export default {
  name: 'EditPassword',
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else {
        if (this.ruleForm.newPassword !== '') {
          this.$refs.ruleForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'))
      } else if (value !== this.ruleForm.newPassword) {
        callback(new Error('两次密码不一致'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        password: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        password: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPassword: [
          { validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onOk () {
      return new Promise((resolve) => {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.$loading.show()
            editPassword({
              ...this.ruleForm
            }).then(res => {
              this.$loading.hide()
              if (res.data === '修改成功') {
                this.$store.dispatch('Logout').then(() => {
                  this.$router.push({ name: 'login' })
                })
                resolve(true)
              } else {
                this.$message.error(res.data)
              }
            }).catch(() => {
              this.$loading.hide()
            })
          }
        })
      })
    }
  }
}
</script>
